<?php
namespace app\admin\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;


/**
 * 定时任务类,从全境拉取商品规格属性任务
 */
class SpuLoader extends Command{


   public function configure(){
       $this->setName('loadGoodsSpuTask')
            ->setDescription('load goods spu and sku data from quanjing');
   }

   public function execute(Input $input, Output $output){
       $output->info('从全境拉取商品规格属性任务执行开始');
       $this->loadGoodsSpuTask($output);
       $output->info('从全境拉取商品规格属性任务执行结束');
   }

    /**
     * 定时任务执行
     */
    public function loadGoodsSpuTask(Output $output){
        ini_set('memory_limit', '-1');
        $list= model('app\common\model\wanlshop\Goods')::where('hasspu',0)->where('spuId','<>','0')->limit(15)->select();
        //全境供应链-获取商品规格信息
        $skuData = $spuData = $goodsData = [];
        foreach ($list as $row){
            $info = loadSkuInfoFromApi($row, $skuData, $spuData);
            if(isset($info['code'])){
                $output->writeln('失败:'.$info['msg']);
                return;
            }

            if ($info) {
                $skuData = array_merge($skuData, $info['skuData']);
                $spuData = array_merge($spuData, $info['spuData']);
                $goodsData[] = ['id' => $info['goods']['id'], 'price' => $info['goods']['price'],'hasspu'=>1];
            }
        }
        if(!$skuData && !$spuData && !$goodsData) return;
        $skuData = array_unique($skuData, SORT_REGULAR);
        $spuData = array_unique($spuData, SORT_REGULAR);
        Db::startTrans();
        try {
            model('app\common\model\wanlshop\Goods')->saveAll($goodsData);
            model('app\common\model\wanlshop\GoodsSku')->saveAll($skuData, false);
            model('app\common\model\wanlshop\GoodsSpu')->saveAll($spuData, false);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $output->writeln($e->getMessage());
        }
    }

}

